package jcurses.widgets;

import jcurses.util.Rectangle;

public class GridFlowLayoutManager extends GridLayoutManager {

	private static Rectangle getGridSize(int countWidgets) {
		int gridWidth = 1;
		int gridHeigth = 1;
		while (gridHeigth * gridWidth < countWidgets) {
			if (gridWidth <= gridHeigth) {
				gridWidth++;
			} else {
				gridHeigth++;
			}
		}
		return new Rectangle(gridWidth, gridHeigth);
	}

	private int x = 0;

	private int y = 0;

	public GridFlowLayoutManager(int countWidgets) {
		super(getGridSize(countWidgets));
	}

	public void addWidget(Widget widget) {
		if (x < this._width && y < this._height) {
			super.addWidget(widget, x, y, 1, 1, ALIGNMENT_CENTER,
					ALIGNMENT_CENTER);
			if (x < this._width - 1) {
				x++;
			} else {
				y++;
				x = 0;
			}
		}
	}

}
